<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>贪食蛇</title>
    <link rel="stylesheet" href="./css/bootstrap.min.css">
    <script src="./js/jquery.min.js"></script>
    <script src="./js/bootstrap.min.js"></script>
    <style>
        #bg {
            width: 400px;
            height: 400px;
            margin: 0 auto;
            position: relative;
            border: 1px solid #ccc;
            margin-top: 20px;
        }
        
        #rule {
            width: 100px;
            height: 400px;
            position: absolute;
            left: -110px;
            border: 1px solid #ccc;
            background-color: #f9f9f9;
        }
        
        #rule button {
            position: absolute;
            bottom: 10px;
            left: 8px;
        }
        
        #count {
            width: 200px;
            height: 400px;
            position: absolute;
            right: -210px;
            border: 1px solid #ccc;
            background-color: #f9f9f9;
        }
    </style>
</head>

<body>

    <div id="bg">
        <div id="rule" style="text-align:center;">
            <h2 style="font-size:16px;margin:10px 0;font-weight:bold;">规则：</h2>
            <p style="color:black;margin:0;">1.不可穿墙</p>
            <p style="color:black;margin:0;">2.蛇头不能触碰蛇身</p>
            <button id="startGame" class="btn btn-primary">开始游戏</button>
        </div>
        <div id="count">
            <h2 style="font-size:16px;margin:10px 0;text-align:center;">当前食量：<span style="color:skyblue;font-size:36px;vertical-align:middle;">0</span></h2>
        </div>
    </div>

    <!-- <button id="testBtn">出现食物按钮</button>
    <button id="move">出击吧，大蛇丸！</button> -->
</body>

</html>
<script>
    $().ready(function() {
        var WIDTH = 400;
        var HEIGHT = 400;
        var SPEED = 100;
        var COUNT = 0;
        var startGame = false;

        function Food() {
            this.size = 20;
            this.color = ['red', 'blue', 'skyblue', 'yellowgreen', 'green', 'black', 'pink', 'palevioletred'];
            this.X = 200; //显示在背景板的中央位置
            this.Y = 180; //显示在背景板的中央位置

            this.show_food = function(flag) { //是否是第一次出现,是的话1，不是为0
                $('#food').remove();
                if (!flag) {
                    this.randCoo();
                }
                var randomKey = Math.floor(Math.random() * this.color.length);
                var foodEle = $("<div id='food'></div>");
                foodEle.css({
                    'position': 'absolute',
                    'left': this.X,
                    'top': this.Y,
                    'width': this.size,
                    'height': this.size,
                    'backgroundColor': this.color[randomKey]
                });
                $("#bg").append(foodEle);
            }

            this.randCoo = function() {
                this.X = Math.floor(Math.random() * 20) * this.size;
                this.Y = Math.floor(Math.random() * 20) * this.size;
            }

        }

        function Snake() {
            //蛇身，初始化三节;
            this.size = 20;
            this.snake_body = [{
                "X": 40,
                "Y": 0,
                'dire': 'down'
            }, {
                "X": 20,
                "Y": 0,
                'dire': 'right'
            }, {
                "X": 0,
                "Y": 0,
                'dire': 'right'
            }]
            this.move_flag = true;
            //显示：
            this.show_snake = function() {
                    $(".sanke").remove()
                    for (var i = 0; i < this.snake_body.length; i++) {
                        var snake_box = $("<div class='sanke'></div>");
                        var color = "black";
                        if (i == 0) {
                            color = "palevioletred";
                        }
                        snake_box.css({
                            'position': 'absolute',
                            'left': this.snake_body[i].X + "px",
                            'top': this.snake_body[i].Y + "px",
                            'width': this.size + "px",
                            'height': this.size + "px",
                            'backgroundColor': color
                        })
                        $("#bg").append(snake_box);
                    }
                }
                //自己移动
            this.move = function() {
                for (var i = this.snake_body.length - 1; i > 0; i--) {
                    this.snake_body[i].X = this.snake_body[i - 1].X
                    this.snake_body[i].Y = this.snake_body[i - 1].Y
                    this.snake_body[i].dire = this.snake_body[i - 1].dire
                }

                switch (this.snake_body[0].dire) {
                    case 'left':
                        this.snake_body[0].X -= this.size;
                        if (this.snake_body[0].X < 0) {
                            this.move_flag = false;
                        }
                        break;
                    case 'right':
                        this.snake_body[0].X += this.size;
                        if (this.snake_body[0].X > WIDTH - this.size) {
                            //this.snake_body[0].X =  WIDTH - this.size
                            this.move_flag = false;
                        }
                        break;
                    case 'up':
                        this.snake_body[0].Y -= this.size;
                        if (this.snake_body[0].Y < 0) {
                            this.move_flag = false;
                        }
                        break;
                    case 'down':
                        this.snake_body[0].Y += this.size;
                        if (this.snake_body[0].Y > HEIGHT - this.size) {
                            this.move_flag = false;
                        }
                        break;
                }

            }
        }

        function Count() {
            this.show_count = function() {
                var countEle = $('#count').find('span');
                countEle.text(COUNT);
            }
        }
        /* *************************************华丽丽的分割线******************************************* */
        //食物对象;
        var food = new Food();
        food.show_food(1);


        $("#testBtn").bind('click', function() {
            food.show_food(0);
        })

        //蛇对象
        var snake = new Snake();
        snake.show_snake();
        $("#move").bind('click', function() {
                snake.move();
                snake.show_snake();
            })
            //计分板对象;
        var countObj = new Count();
        //速度定时器;
        // var speed_timer = setInterval(function(){
        //     SPEED -= 50
        // },5000)

        function timer_func() {
            if (snake.move_flag) {
                var gameover = false;
                var timer = setTimeout(function() {
                    clearTimeout(timer)
                    snake.move();
                    for (var i = snake.snake_body.length - 1; i > 0; i--) {
                        if (snake.snake_body[0].X == snake.snake_body[i].X && snake.snake_body[0].Y == snake.snake_body[i].Y) {
                            gameover = true;
                            alert('自杀，游戏结束');
                        }
                    }
                    //吃到食物增加长度;
                    if (snake.snake_body[0].X == food.X && snake.snake_body[0].Y == food.Y) {
                        snake.snake_body.unshift({
                            'X': food.X,
                            'Y': food.Y,
                            'dire': snake.snake_body[0].dire
                        });
                        food.show_food(0);
                        COUNT += 1
                        countObj.show_count();
                    }
                    //自杀判断:
                    snake.show_snake();

                    if (!gameover) {
                        timer_func()
                    }
                }, SPEED)
            } else {
                alert("游戏结束");
            }
        }

        $("#startGame").bind('click', function() {
                if (!startGame) {
                    startGame = !startGame;
                    timer_func();
                    $(this).text('暂停游戏');
                } else {
                    startGame = !startGame;
                    $(this).text('开始游戏');
                }
            })
            // if(false){
            //     timer_func();
            // }

        $(window).bind('keydown', function(event) {
            switch (parseInt(event.keyCode)) {
                case 37: //left_kdy
                    if (snake.snake_body[0].dire != 'right' && snake.snake_body[0].dire != 'left') {
                        snake.snake_body[0].dire = 'left'
                    }
                    break;
                case 38: //up_key
                    if (snake.snake_body[0].dire != 'up' && snake.snake_body[0].dire != 'down') {
                        snake.snake_body[0].dire = 'up'
                    }
                    break;
                case 39: //up_right
                    if (snake.snake_body[0].dire != 'right' && snake.snake_body[0].dire != 'left') {
                        snake.snake_body[0].dire = 'right'
                    }
                    break;
                case 40: //up_down
                    if (snake.snake_body[0].dire != 'up' && snake.snake_body[0].dire != 'down') {
                        snake.snake_body[0].dire = 'down'
                    }
                    break;
            }
        })
    })
</script>